 package com.cloudcc.mobile.view.dynamic;

 import android.app.AlertDialog;
 import android.app.AlertDialog.Builder;
 import android.app.Dialog;
 import android.content.BroadcastReceiver;
 import android.content.Context;
 import android.content.DialogInterface;
 import android.content.Intent;
 import android.content.IntentFilter;
 import android.os.Bundle;
 import android.view.LayoutInflater;
 import android.view.View;
 import android.view.View.OnClickListener;
 import android.view.ViewGroup.LayoutParams;
 import android.view.animation.AnimationUtils;
 import android.view.inputmethod.InputMethodManager;
 import android.widget.BaseAdapter;
 import android.widget.Button;
 import android.widget.EditText;
 import android.widget.ImageView;
 import android.widget.ListView;
 import android.widget.ScrollView;
 import android.widget.TextView;

 import com.cloudcc.cloudframe.bus.DynamicEventList.SendCommentEvent;
 import com.cloudcc.cloudframe.bus.EventEngine;
 import com.cloudcc.cloudframe.bus.EventList.DeleteCommentEvent;
 import com.cloudcc.cloudframe.bus.EventList.DynamicSingleEvent;
 import com.cloudcc.cloudframe.bus.EventList.VoteDynamicEvent;
 import com.cloudcc.cloudframe.bus.IEventLife;
 import com.cloudcc.cloudframe.model.DynamicModel;
 import com.cloudcc.cloudframe.model.DynamicModel.Comments;
 import com.cloudcc.cloudframe.util.GsonUtil;
 import com.cloudcc.cloudframe.util.ListUtils;
 import com.cloudcc.cloudframe.util.LogUtils;
 import com.cloudcc.cloudframe.util.StringUtils;
 import com.cloudcc.mobile.AppContext;
 import com.cloudcc.mobile.R;
 import com.cloudcc.mobile.ReceiverConstant;
 import com.cloudcc.mobile.adapter.DynamicAdapter;
 import com.cloudcc.mobile.adapter.DynamicAdapter.OnItemListener;
 import com.cloudcc.mobile.adapter.DynamicCommentAdapter;
 import com.cloudcc.mobile.adapter.DynamicCommentAdapter.MyOnItemClickListener;
 import com.cloudcc.mobile.entity.MyChatter;
 import com.cloudcc.mobile.manager.RunTimeManager;
 import com.cloudcc.mobile.manager.UrlManager;
 import com.cloudcc.mobile.manager.UserManager;
 import com.cloudcc.mobile.presenter.DynamicControl;
 import com.cloudcc.mobile.util.LoadingUtils;
 import com.cloudcc.mobile.util.Tools;
 import com.cloudcc.mobile.util.UrlTools;
 import com.cloudcc.mobile.view.activity.AtContaxtActivity;
 import com.cloudcc.mobile.view.activity.BeauInfoActivity;
 import com.cloudcc.mobile.view.activity.MyWebActivity;
 import com.cloudcc.mobile.view.activity.Myinformation;
 import com.cloudcc.mobile.view.base.BaseActivity;
 import com.cloudcc.mobile.view.mymodel.isshuaxin;
 import com.cloudcc.mobile.view.web.IWebView;
 import com.cloudcc.mobile.weight.DialogUtils;
 import com.cloudcc.mobile.weight.ListViewForScrollView;
 import com.cloudcc.mobile.weight.MyDialogClickListener;
 import com.litesuits.android.log.Log;
 import com.mypage.utils.SaveTemporaryData;
 import com.mypage.utils.VoiceMediaManager;

 import java.util.ArrayList;
 import java.util.List;

 import butterknife.Bind;
 import butterknife.OnClick;
 import de.greenrobot.event.EventBus;

 import static com.cloudcc.mobile.R.id.editText;

 /**
 * 动态 详情 考虑兼容
 * 
 * @author seven
 * 
 */
public class DynamicActivity extends BaseActivity implements
		MyOnItemClickListener, IEventLife, OnItemListener {
	private static final int CHATER_DETAIL_ACTIVITY_AT = 7000;
	private String mEns = RunTimeManager.getInstance().getlanguage();

	public static final String KEY_CHATID = "chatId";
	public static final String KEY_DYNAMIC = "myChatter";

	@Bind(R.id.back)
	ImageView back;
	@Bind(R.id.refresh)
	ImageView ivRefresh;
	@Bind(R.id.listview)
	ListViewForScrollView mDetail;
	@Bind(R.id.listview_c)
	ListViewForScrollView mComments;

	@Bind(R.id.scrollview)
	ScrollView scLayout;
	@Bind(R.id.dynamic_detail_bottomline)
	View bottomLine;

	@Bind(R.id.ed_comment)
	EditText etCommentContent;

	private DynamicModel dynamicModel;

	private DynamicCommentAdapter commentAdapter;
	private DynamicAdapter dynamicAdapter;

	private DynamicControl dynamicPresenter = new DynamicControl();

	@Override
	public void init(Bundle savedInstanceState) {
		super.init(savedInstanceState);
		register();
		dynamicModel = new DynamicModel();
		MyChatter myChatter = (MyChatter) getIntent().getSerializableExtra(
				KEY_DYNAMIC);
		if (myChatter != null) {
			dynamicModel = GsonUtil.covertBean(myChatter, DynamicModel.class);
			ArrayList<DynamicModel> arrayList = new ArrayList<DynamicModel>();
			arrayList.add(dynamicModel);
			fillDynamic(arrayList);
		}
		String dynamicId = getIntent().getStringExtra(KEY_CHATID);
		if (dynamicId != null) {
			dynamicModel.id = dynamicId;
		}
		refreshData(dynamicModel.id);
		initReceiver();
	}

	private void fillDynamic(List<DynamicModel> data) {
		Log.d("jibian", "filldatacommon");
		dynamicModel = data.get(0);
		Log.d("siyouyemiande", dynamicModel.targetId + "scds");
		if (dynamicAdapter == null) {
			dynamicAdapter = new DynamicAdapter(mContext,
					dynamicModel.targetId, dynamicModel.targetIdname,"true");
			dynamicAdapter.setOnItemtListener(this);
			mDetail.setAdapter(dynamicAdapter);
		}
		dynamicAdapter.changeData(data);

		fillComment(dynamicModel.comments);
		setListViewHeightBasedOnChildren(mContext, mDetail);
	}

	private void fillComment(List<Comments> comments) {
		if (ListUtils.isEmpty(comments)) {
			bottomLine.setVisibility(View.INVISIBLE);
			return;
		}
		commentAdapter = new DynamicCommentAdapter(mContext);
		commentAdapter.setMyOnItemClickListener(this);
		commentAdapter.changeData(dynamicModel.comments);
		mComments.setAdapter(commentAdapter);
		scLayout.fullScroll(ScrollView.FOCUS_DOWN);
		bottomLine.setVisibility(View.VISIBLE);
		setListViewHeightBasedOnChildren(mContext, mComments);
	}

	@OnClick(R.id.r_fasong)
	public void clickSend() {
		
		

		if ("".equals(etCommentContent.getText().toString().trim())) {
			Log.d("showWainting", "发送的评论"
					+ etCommentContent.getText().toString());
			if ("en".equals(mEns)) {
				Tools.showInfo(mContext, "Comments can not be empty");
			}else{
				Tools.showInfo(mContext, "评论不能为空");
		}


		} else {
			if ("en".equals(mEns)) {
				showWainting("Sending comment...");
			}else{
				showWainting("正在发送评论...");
		}
			
			dynamicPresenter.sendComment(etCommentContent.getText().toString(),
					dynamicModel.id);
		}
		InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
		imm.hideSoftInputFromWindow(etCommentContent.getWindowToken(), 0) ;
	}

	private void refreshData(String id) {
		ivRefresh.startAnimation(AnimationUtils.loadAnimation(mContext,
				R.anim.rotate_data_refreshing));
		dynamicPresenter.getDynamic(id);
	}

	/**
	 * 发送 评论 结束
	 * 
	 * @param event
	 */
	public void onEventMainThread(SendCommentEvent event) {
		dismissWainting();
		if (event.isError()) {
			if ("en".equals(mEns)) {
				Tools.showInfo(mContext, "Comment failed");
			}else{
				Tools.showInfo(mContext, "评论失败");
		}
			
			return;
		}
		if ("en".equals(mEns)) {
			Tools.showInfo(mContext, "Comments are successful");
		}else{
			Tools.showInfo(mContext, "评论成功");
	}
		
		etCommentContent.setText("");
		refreshData(dynamicModel.id);
	}

	/**
	 * 获得
	 * 
	 * @param event
	 */
	public void onEventMainThread(DynamicSingleEvent event) {
		ivRefresh.postDelayed(new Runnable() {
			@Override
			public void run() {
				ivRefresh.clearAnimation();
			}
		}, 150);

		if (event.isError()) {
			return;
		}
		fillDynamic(event.getData().data);
	}

	/**
	 * 删除评论
	 * 
	 * @param event
	 */
	public void onEventMainThread(DeleteCommentEvent event) {
		if ("en".equals(mEns)) {
			Tools.showInfo(mContext, event.isOk() ? "Delete comment success" : "Delete comment failed");
		}else{
			Tools.showInfo(mContext, event.isOk() ? "删除评论成功" : "删除评论失败");
			if(event.isOk()){
				refreshData(dynamicModel.id);
			}
	}
	
	}

	@Override
	public void onClickMore(Comments t, int posf) {
		final int pos = posf;

		String s = "赞";
		String s1 = "删除";

		if ("en".equals(mEns)) {
//			 s = "Thumbs up";
			 s1 = "delete";
		}else{
//			 s = "赞";
			 s1 = "删除";
	}


		final String[] items = new String[] { s1 };

		boolean isMe = StringUtils.equals(
				UserManager.getManager().getUser().userId, t.authorId);
	if ("en".equals(mEns)) {
		// #1 当前是赞了还是没攒
//				if (t.ispraised) {// 是我的 我已经攒了
//					items[0] = "Dislike";
//				}
				if (!isMe) {
					items[0] = "Reply";
				}
		}else{
//			// #1 当前是赞了还是没攒
//			if (t.ispraised) {// 是我的 我已经攒了
//				items[0] = "取消赞";
//			}
			if (!isMe) {
				items[0] = "回复";
			}
	}
		

		Builder builder = new Builder(mContext);
		builder.setItems(items, new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				Comments comment = commentAdapter.getItem(pos);
				switch (which) {
				case 0:// 取消 或者 赞
//					comment.ispraised = !comment.ispraised;
//					commentAdapter.notifyDataSetChanged();
//					dynamicPresenter
//							.likeComment(comment.id, !comment.ispraised);

					if (StringUtils.equals(items[0], "回复")) {
						String a = "@[" + comment.authorIdname + "]";
						etCommentContent.setText(a);
						etCommentContent.setSelection(a.length());
					} else {
						deleteComment(pos);
					}
					break;
//				case 1:// 回复或者删除
//					if (StringUtils.equals(items[1], "回复")) {
//						String a = "@[" + comment.authorIdname + "]";
//						etCommentContent.setText(a);
//						etCommentContent.setSelection(a.length());
//					} else {
//						deleteComment(pos);
//					}
//					break;
				}
			}
		}).setCancelable(true).show();

	}

	private void deleteComment(final int position) {
		if ("en".equals(mEns)) {
			
			
			DialogUtils.showWarn(mContext, "Delete comment", "Are you sure you want to delete this reply?？",
					new MyDialogClickListener() {
						@Override
						public void onClickPositive(Dialog dialog) {
							super.onClickPositive(dialog);
							dialog.cancel();
							Comments comment = commentAdapter.getItem(position);
							dynamicPresenter.deleteComment(comment.id);
							commentAdapter.removeItem(comment);
						}

						@Override
						public void onClickNegative(Dialog dialog) {
							super.onClickNegative(dialog);
							dialog.cancel();
						}
					});
		}else{
		
	
		DialogUtils.showWarn(mContext, "删除评论", "确定删除这条回复吗？",
				new MyDialogClickListener() {
					@Override
					public void onClickPositive(Dialog dialog) {
						super.onClickPositive(dialog);
						dialog.cancel();
						Comments comment = commentAdapter.getItem(position);
						dynamicPresenter.deleteComment(comment.id);
						commentAdapter.removeItem(comment);
						refreshData(dynamicModel.id);
					}

					@Override
					public void onClickNegative(Dialog dialog) {
						super.onClickNegative(dialog);
						dialog.cancel();
					}
				});
	}
		}

	@OnClick(R.id.r_quan)
	public void clickAiTe() {
		Intent intent = new Intent(mContext, AtContaxtActivity.class);
		startActivityForResult(intent, CHATER_DETAIL_ACTIVITY_AT);
	}

	@OnClick(R.id.refresh)
	public void clickRefresh() {
		refreshData(dynamicModel.id);
	}

	@Override
	public int getLayoutId() {
		return R.layout.dynamic_detail;
	}

	@OnClick(R.id.back)
	public void clickedBack() {
		finish();
	}

	@Override
	public void register() {
		EventEngine.register(this);
	}

	@Override
	public void unRegister() {
		EventEngine.uregister(this);

	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		unRegister();
	}

	@Override
	public void onClickLink(DynamicModel t) {
		Log.d("dianjihuodong", "dianjihuodong ");
		Intent intent = new Intent(mContext, MyWebActivity.class);
		intent.putExtra(IWebView.KEY_URL, t.linkValue);
		if ("en".equals(mEns)) {
			intent.putExtra(IWebView.KEY_NAME,StringUtils.isBlank(t.linkName) ? "Share links" : "Share links-" + t.linkName);
		}else{
			intent.putExtra(IWebView.KEY_NAME,StringUtils.isBlank(t.linkName) ? "分享链接" : "分享链接-" + t.linkName);
	}
		
		mContext.startActivity(intent);
	}

	@Override
	public void onClickUser(DynamicModel t) {
		enterUserInfo(t);
	}

	private void enterUserInfo(DynamicModel t) {
		Intent intent = new Intent(mContext, Myinformation.class);
		SaveTemporaryData.mSmart = "";
		intent.putExtra("userId", t.authorId);
		intent.putExtra("name", t.authorIdname);


		startActivity(intent);
	}

	@Override
	public void onClickComment(DynamicModel t) {

	}

	@Override
	public void onClickLike(DynamicModel t, View v) {
		dynamicPresenter.like(t.id, t.ispraised);
	}

	@Override
	public void onClickEventOrTask(DynamicModel t) {
		Log.d("dianjihuodong1", "dianjihuodong ");
		Intent intent = new Intent(DynamicActivity.this, BeauInfoActivity.class);
		intent.putExtra("web", t.taskIdOrEventId);
		if((t.taskIdOrEventId.startsWith("bef"))||((t.taskIdOrEventId.startsWith("bfa")))){
			intent.putExtra("web.url",UrlManager.getRootUrl()+ UrlTools.getObjectUrl_z(t.taskIdOrEventId));
			intent.putExtra("from", "dynamicactivity");
		}else{
			intent.putExtra("web.url",UrlManager.getRootUrl()+ UrlTools.getObjectUrl(t.taskIdOrEventId));
		}		
		startActivity(intent);
		/*
		 * AppContext.urlString = UrlManager.APP_UR + "/" +
		 * UrlTools.getTaskOrEventUrl(t.taskIdOrEventId); Intent intent = new
		 * Intent(mContext, RelevantActivtiy.class); intent.putExtra("web",
		 * t.taskIdOrEventId); intent.putExtra("web.url", AppContext.urlString);
		 * mContext.startActivity(intent);
		 */
//		Intent intent = new Intent(mContext, CloudWebViewActivity.class);
//		intent.putExtra(ExtraConstant.EXTRA_URL, UrlManager.getManager()
//				.getTaskOrScheduleDetailUrl(t.taskIdOrEventId));
//		MonitorParam monitorParam = new MonitorParam(
//				new String[] { "m=delete" }, WebSyncDefaultProxy.STEP_START,
//				new String[] { "taskcondition=today", "m=list&objid=task",
//						"eventcondition=today" }, true,
//				WebSyncDefaultProxy.STEP_START);
//		MonitorParam monitorParam2 = new MonitorParam(
//				new String[] { "m=save" }, WebSyncDefaultProxy.STEP_START,
//				new String[] { "m=query" }, true,
//				WebSyncDefaultProxy.STEP_OVERRIDEURL);
//		MonitorParam monitorParam3 = new MonitorParam(new String[] {
//				"taskcondition=today", "eventcondition=today" },
//				WebSyncDefaultProxy.STEP_START, new String[] {
//						"taskcondition=today", "eventcondition=today" }, true,
//				WebSyncDefaultProxy.STEP_START);
//		monitorParam3.isCallBack = false;
//		intent.putExtra(
//				"callback",
//				WebSyncDefaultProxy
//						.creatDefaultProxy(
//								ReceiverConstant.RECEIVE_REFRESH_SCHEDULE)
//						.addMonitorParam(monitorParam)
//						.addMonitorParam(monitorParam2)
//						.addMonitorParam(monitorParam3).addHomeMonitor());
//
//		startActivity(intent);

	}
	protected DynamicControl mControl = new DynamicControl();
	@Override
	public void onClickCollect(DynamicModel t) {
		mControl.Favorite(t.id, t.isfavorited);
	}

	@Override
	public void onClickDelete(DynamicModel t, int pos) {
		if (StringUtils.equals(t.authorId,
				UserManager.getManager().getUser().userId)) {
			showDialog(t, pos);
		}

	}

	class Ddialog {
		private TextView name;
		private Button cancle, sure;
	}

	protected void showDialog(final DynamicModel t, int pos) {
		final Ddialog dd = new Ddialog();
		LayoutInflater inflater = LayoutInflater.from(mContext);
		View layout = inflater.inflate(R.layout.define_deleted, null);
		dd.name = (TextView) layout.findViewById(R.id.titletitle);
		if ("en".equals(mEns)) {
			dd.name.setText("Are you sure you want to delete this post？");
		}else{
			dd.name.setText("确定删除这条微贴吗？");
	}
		
		final AlertDialog builder = new Builder(mContext).create();
		builder.setView(layout);
		builder.show();
		Button cancle = (Button) layout.findViewById(R.id.quxiaocanle);
		cancle.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				builder.cancel();
			}
		});
		Button sure = (Button) layout.findViewById(R.id.quedingsure);
		sure.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				dynamicPresenter.delete(t.id);
				finish();
				isshuaxin event = new isshuaxin();
				event.isshua = true;
				EventBus.getDefault().post(event);
				// dynamicAdapter.removeItem(t);
				builder.cancel();
			}
		});

	}

	@Override
	public void onClickDownload(DynamicModel t, int pos) {
		MyChatter covertBean = GsonUtil.covertBean(t, MyChatter.class);
		LoadingUtils loading = new LoadingUtils(mContext, covertBean, pos);
		loading.loadingFile();

	}

	@Override
	public void onClickRelation(DynamicModel t) {

		Log.d("dianjishijian2", "dianjihuodong ");
		AppContext.urlString = UrlManager.getManager().addReturnUrl(
				UrlManager.getRootUrl() + UrlTools.getObjectUrl_z(t.targetId));
		Intent intent = new Intent(mContext, BeauInfoActivity.class);
		intent.putExtra("web", t.targetId);
		intent.putExtra(
				"web.url",
				UrlManager.getManager().addReturnUrl(
						UrlManager.getRootUrl()
								+ UrlTools.getObjectUrl_z(t.targetId)));
		mContext.startActivity(intent);

	}

	@Override
	public void onClickVote(DynamicModel t, String option) {

		showWainting();

		dynamicPresenter.sendVote(t.id, option);
	}

	public void onEventMainThread(VoteDynamicEvent event) {
		dismissWainting();
		if (event.isError()) {
			return;
		}
		refreshData(dynamicModel.id);
	}

	@Override
	public void onClickBody(DynamicModel t) {

	}

	/** 回调 * */
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (requestCode == CHATER_DETAIL_ACTIVITY_AT && resultCode == RESULT_OK) {
			String a = data.getStringExtra("name");
			String[] c = a.split(",");
			for (int i = 0; i < c.length; i++) {
				if (!c[i].equals("")) {
					etCommentContent.append(" @[" + c[i] + "]");
				}
			}
		}
	}

	public static void setListViewHeightBasedOnChildren(Context context,
			ListView listView) {
		if (listView == null)
			return;
		BaseAdapter listAdapter = (BaseAdapter) listView.getAdapter();

		if (listAdapter == null) {
			return;
		}
		listAdapter.notifyDataSetChanged();
		int totalHeight = 0;
		for (int i = 0; i < listAdapter.getCount(); i++) {
			View listItem = listAdapter.getView(i, null, listView);
			listItem.measure(0, 0);
			totalHeight += listItem.getMeasuredHeight();
		}
		LayoutParams params = listView.getLayoutParams();
		params.height = totalHeight;
		params.width = LayoutParams.MATCH_PARENT;
		listView.setLayoutParams(params);
		listView.requestLayout();// 664- 1007 =343
		LogUtils.d("app", "高度：" + listView + "::" + params.height);
	}

	private SyncReceiver mSyncReceiver;

	private void initReceiver() {
		mSyncReceiver = new SyncReceiver();
		IntentFilter filter = new IntentFilter();
		filter.addAction(ReceiverConstant.RECEIVE_REFRESH_SCHEDULE);
		mContext.registerReceiver(mSyncReceiver, filter);
	}

	private class SyncReceiver extends BroadcastReceiver {
		@Override
		public void onReceive(Context context, Intent intent) {
			refreshData(dynamicModel.id);
		}
	}
	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		VoiceMediaManager.pause();
	}
}
